import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import type { UserInfo, UserState } from '@/types/user';
import useCache from './useCache';
import { CacheKeyEnum } from '@/constants/cacheKey';
import { loginApi, getUserInfoApi, updateUserInfoApi } from '../mock/userMock';

interface UseUserResult extends UserState {
  // 获取用户信息
  fetchUserInfo: () => Promise<void>;
  // 登录
  login: (username: string, password: string, rememberMe?: boolean) => Promise<boolean>;
  // 登出
  logout: () => void;
  // 更新用户信息
  updateUserInfo: (userInfo: Partial<UserInfo>) => void;
}

/**
 * 用户相关的Hook，用于管理用户信息和状态
 */
export default function useUser(): UseUserResult {
  const [userState, setUserState] = useState<UserState>({
    userInfo: null,
    isLoggedIn: false,
    loading: false,
  });
  
  const navigate = useNavigate();
  const cache = useCache();

  // 初始化用户信息
  const initUserInfo = useCallback(async () => {
    try {
      // 检查缓存中是否有用户信息，使用新的统一API获取
      const cachedData = cache.get<UserInfo>(CacheKeyEnum.USER);
      if (cachedData && cachedData.username) {
        // 调用获取用户信息API获取完整用户信息
        const userInfo = await getUserInfoApi(cachedData.username);
        
        if (userInfo) {
          setUserState(prev => ({
            ...prev,
            userInfo,
            isLoggedIn: true,
          }));
        } else {
          // 如果API调用失败，移除缓存
          // cache.remove(CacheKeyEnum.USER);
        }
      }
    } catch (error) {
      console.error('Failed to initialize user info:', error);
      // 清除无效的缓存数据
      // cache.remove(CacheKeyEnum.USER);
    }
  }, [cache, setUserState]);

  // 初始化用户信息
  useEffect(() => {
    const initializeUser = async () => {
      await initUserInfo();
    };
    initializeUser();
  }, [initUserInfo]);

  // 获取用户信息
  const fetchUserInfo = async () => {
    setUserState(prev => ({ ...prev, loading: true }));
    try {
      // 从缓存中获取用户信息，使用新的统一API获取
      const cachedUser = cache.get<UserInfo>(CacheKeyEnum.USER);
      if (cachedUser && cachedUser.username) {
        // 调用获取用户信息API
        const userInfo = await getUserInfoApi(cachedUser.username);
        
        if (userInfo) {
          console.log('用户信息加载成功:', userInfo); // 调试信息
          setUserState(prev => ({
            ...prev,
            userInfo,
            isLoggedIn: true,
          }));
        }
      }
    } catch (error) {
      console.error('Failed to fetch user info:', error);
    } finally {
      setUserState(prev => ({ ...prev, loading: false }));
    }
  };

  // 登录
  const login = async (username: string, password: string, rememberMe = false): Promise<boolean> => {
    setUserState(prev => ({ ...prev, loading: true }));
    try {
      // 调用登录API
      const userInfo = await loginApi(username, password);
      
      if (userInfo) {
        // 保存用户信息到缓存，使用新的统一API设置
        cache.set(CacheKeyEnum.USER, userInfo);
        
        setUserState(prev => ({
          ...prev,
          userInfo,
          isLoggedIn: true,
        }));
        
        return true;
      }
      return false;
    } catch (error) {
      console.error('Login failed:', error);
      return false;
    } finally {
      setUserState(prev => ({ ...prev, loading: false }));
    }
  };

  // 登出
  const logout = () => {
    // 清除缓存中的用户信息
    // cache.remove(CacheKeyEnum.USER);
    // 更新用户状态
    setUserState({
      userInfo: null,
      isLoggedIn: false,
      loading: false,
    });
    // 重定向到登录页面
    navigate('/login');
  };

  // 更新用户信息
  const updateUserInfo = async (userInfo: Partial<UserInfo>) => {
    try {
      if (!userState.userInfo?.id) return;
      
      // 调用更新用户信息API
      const updatedUserInfo = await updateUserInfoApi(userState.userInfo.id, userInfo);
      
      if (updatedUserInfo) {
        // 更新状态
        setUserState(prev => ({
          ...prev,
          userInfo: { ...prev.userInfo, ...updatedUserInfo },
        }));
        
        // 更新缓存，使用新的统一API设置
        cache.set(CacheKeyEnum.USER, updatedUserInfo);
      }
    } catch (error) {
      console.error('Failed to update user info:', error);
    }
  };

  return {
    ...userState,
    fetchUserInfo,
    login,
    logout,
    updateUserInfo,
  };
}